package com.app.studyroom;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.adapter.UserAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrUser.PageUserListRequest;
import com.app.studyroom.api.model.ssrUser.PageUserListResponse;
import com.app.studyroom.api.model.ssrUser.UserDeleteRequest;
import com.app.studyroom.api.model.ssrUser.UserItem;
import com.app.studyroom.api.model.ssrUser.UserSaveRequest;
import com.app.studyroom.api.model.ssrUser.UserUpdateRequest;
import com.app.studyroom.dialog.UserEditDialog;
import com.app.studyroom.mapper.AreaNameToIdMapper;
import com.app.studyroom.model.MyMultiSelectionSpinner;
import com.google.gson.Gson;
import com.zeeshan.material.multiselectionspinner.MultiSelectionSpinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AdminUserControlActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private UserAdapter userAdapter;
    private List<UserItem> userList = new ArrayList<>();
    private ApiService apiService;
    private ImageView ic_back;

    private EditText editID, editPhone, editStudentID,editClassID, editUserName, editPassword;
    private Spinner spinnerRole;
    private MyMultiSelectionSpinner spinnerAreaMulti ;
    private Button btnAddUser;
    private String token;

    //分页显示
    private int currentPage = 1;
    private final int pageSize = 11;

    //按时刷新
    private final long REFRESH_INTERVAL_MS = 60 * 1000; // 一分钟
    private final android.os.Handler refreshHandler = new android.os.Handler();

    public boolean isEditDialogShowing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_control);

        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        token = sp.getString("token", "");

        recyclerView = findViewById(R.id.rows_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        ic_back = findViewById(R.id.ic_back);
        ic_back.setOnClickListener(v -> onBackPressed());

        userAdapter = new UserAdapter(this, userList, new UserAdapter.OnUserActionListener() {
            @Override
            public void onEdit(UserItem user) {
                updateUser(user);
            }
            @Override
            public void onDelete(long userId) {
                deleteUser(userId);
            }
        });
        recyclerView.setAdapter(userAdapter);

        apiService = ApiClient.getClient().create(ApiService.class);

        editID = findViewById(R.id.editID);
        editPhone = findViewById(R.id.editPhone);
        editStudentID = findViewById(R.id.editStudentID);
        editClassID = findViewById(R.id.editClassID);
        editUserName = findViewById(R.id.editUserName);
        editPassword = findViewById(R.id.editPassword);
        spinnerRole = findViewById(R.id.spinnerRole);
        btnAddUser = findViewById(R.id.btnAddUser);
        spinnerAreaMulti = findViewById(R.id.spinnerAreaMulti);


        String[] areaNames = AreaNameToIdMapper.getAllAreaNames();
        ArrayAdapter<String> areaAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, areaNames);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


        ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{"用户", "区域管理员"});
        roleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerRole.setAdapter(roleAdapter);

        spinnerRole.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedRole = parent.getItemAtPosition(position).toString();
                if ("用户".equals(selectedRole)) {
                    spinnerAreaMulti.setEnabled(false);          // 禁用控件
                    spinnerAreaMulti.setAlpha(0.5f);             // 设置半透明视觉提示
                    spinnerAreaMulti.clearSelectionOnly();                    // 清除已选区域（可选）

                    editClassID.setEnabled(true);
                    editClassID.setAlpha(1.0f);
                } else if ("区域管理员".equals(selectedRole)) {
                    spinnerAreaMulti.setEnabled(true);           // 启用控件
                    spinnerAreaMulti.setAlpha(1.0f);             // 恢复不透明

                    editClassID.setEnabled(false);
                    editClassID.setAlpha(0.5f);

                    editClassID.setText("");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });



        btnAddUser.setOnClickListener(v -> {
            String zjh = editID.getText().toString().trim();
            String phone = editPhone.getText().toString().trim();
            String number = editStudentID.getText().toString().trim();
            String classnumber = editClassID.getText().toString().trim();
            String name = editUserName.getText().toString().trim();
            String password = editPassword.getText().toString().trim();
            String role = spinnerRole.getSelectedItem().toString();

            // 使用 MultiSelectionSpinner 获取选中的区域名称

            List<String> selectedAreaNames = new ArrayList<>();
            List<Object> selectedItems = spinnerAreaMulti.getSelectedItems();

            if ("区域管理员".equals(role) && (selectedItems == null || selectedItems.isEmpty())) {
                Toast.makeText(this, "请至少选择一个区域", Toast.LENGTH_SHORT).show();
                return;
            }

            if (selectedItems != null) {
                for (Object obj : selectedItems) {
                    selectedAreaNames.add(obj.toString());
                }
            }


            // 校验空字段
            if (zjh.isEmpty() || phone.isEmpty() || number.isEmpty() || name.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            // 将区域名称转换为 ID（拼接成逗号分隔的字符串，如："101,102"）
            List<String> areaIdList = new ArrayList<>();
            for (String areaName : selectedAreaNames) {
                String areaId = AreaNameToIdMapper.getIdByName(areaName);
                if (areaId != null) areaIdList.add(areaId);
            }
            String areaIdString = String.join(",", areaIdList);

            // 构造保存请求（注意：后端需支持多个区域 ID，以字符串形式接收）
            UserSaveRequest saveRequest = new UserSaveRequest(name, zjh, phone, number, password, role, areaIdString);
            saveRequest.setClassNum(classnumber);
            apiService.userSave(token, saveRequest).enqueue(new Callback<ApiResponse<Object>>() {
                @Override
                public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        ApiResponse<Object> resp = response.body();
                        if (resp.getCode() == 200) {
                            Toast.makeText(AdminUserControlActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                            clearForm();
                            loadUserList();
                        } else {
                            Toast.makeText(AdminUserControlActivity.this, resp.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(AdminUserControlActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }



                @Override
                public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                    Toast.makeText(AdminUserControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });

        //区域多选框
        List<String> areaNameList = Arrays.asList(AreaNameToIdMapper.getAllAreaNames());
        spinnerAreaMulti.setItems(areaNameList);  // 设置区域列表
        loadUserList();

        Button btnPrev = findViewById(R.id.btnPrevPage);
        Button btnNext = findViewById(R.id.btnNextPage);

        btnPrev.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                loadUserList();
            } else {
                Toast.makeText(this, "已经是第一页", Toast.LENGTH_SHORT).show();
            }
        });
        btnNext.setOnClickListener(v -> {
            currentPage++;
            loadUserList();
        });



    }
    @Override
    protected void onResume() {
        super.onResume();
        refreshHandler.post(refreshRunnable);
    }
    @Override
    protected void onPause() {
        super.onPause();
        refreshHandler.removeCallbacks(refreshRunnable);
    }

    private void clearForm() {
        editID.setText("");
        editPhone.setText("");
        editStudentID.setText("");
        editClassID.setText("");
        editUserName.setText("");
        editPassword.setText("");
        spinnerRole.setSelection(0);
        // 清空多选区域
        if (spinnerAreaMulti != null) {
            spinnerAreaMulti.clearSelectionOnly();                    // 清除已选区域（可选）
        }
    }
    public void loadUserList() {
        PageUserListRequest request = new PageUserListRequest(currentPage, pageSize);

        apiService.pageUserList(token, request).enqueue(new Callback<PageUserListResponse>() {
            @Override
            public void onResponse(Call<PageUserListResponse> call, Response<PageUserListResponse> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getData() != null) {
                    List<UserItem> userList = response.body().getData().getData();
                    userAdapter.setUserList(userList);

                    // 控件更新
                    TextView tvPageIndicator = findViewById(R.id.tvPageIndicator);
                    Button btnPrev = findViewById(R.id.btnPrevPage);
                    Button btnNext = findViewById(R.id.btnNextPage);

                    tvPageIndicator.setText("第 " + currentPage + " 页");

                    btnPrev.setEnabled(currentPage > 1);
                    btnPrev.setAlpha(currentPage > 1 ? 1.0f : 0.4f);

                    int total = response.body().getData().getTotal();
                    boolean isLastPage = currentPage * pageSize >= total;

                    btnNext.setEnabled(!isLastPage);
                    btnNext.setAlpha(!isLastPage ? 1.0f : 0.4f);


                } else {
                    Toast.makeText(AdminUserControlActivity.this, "加载用户列表失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<PageUserListResponse> call, Throwable t) {
                Toast.makeText(AdminUserControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void updateUser(UserItem user) {
        UserUpdateRequest updateRequest = new UserUpdateRequest(
                user.getId(),
                user.getUserName(),
                user.getUserZjh(),
                user.getUserSjh(),
                user.getUserNumber(),
                user.getUserBs(),
                user.getQy()
        );
        updateRequest.setUserImage(user.getUserImage());
        updateRequest.setIsBooking(user.getIsBooking());
        updateRequest.setClassNum(user.getClassNum());

        Log.d("UpdateRequest", new Gson().toJson(updateRequest));
        apiService.userUpdate(token, updateRequest).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Object> resp = response.body();
                    if (resp.getCode() == 200) {
                        Toast.makeText(AdminUserControlActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        loadUserList();
                    } else {
                        // ⚠️ 业务失败，显示后端返回的 message
                        Toast.makeText(AdminUserControlActivity.this, resp.getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AdminUserControlActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(AdminUserControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void deleteUser(long userId) {
        UserDeleteRequest deleteRequest = new UserDeleteRequest(userId);

        apiService.userDelete(token, deleteRequest).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Object> resp = response.body();
                    if (resp.getCode() == 200) {
                        Toast.makeText(AdminUserControlActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        loadUserList();
                    } else {
                        // ⚠️ 业务失败，显示后端返回的 message
                        Toast.makeText(AdminUserControlActivity.this, resp.getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AdminUserControlActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(AdminUserControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1003 && resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();
            UserEditDialog.selectedAvatarUri = uri;

            if (UserEditDialog.imgAvatar != null) {
                UserEditDialog.imgAvatar.setImageURI(uri);
            }
            if (UserEditDialog.btnUploadAvatar != null) {
                UserEditDialog.btnUploadAvatar.setText("已选择头像");
            }

//            Toast.makeText(this, "已选择头像，将在保存时上传", Toast.LENGTH_SHORT).show();  测试部分
        }
    }
    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            loadUserList();
            refreshHandler.postDelayed(this, REFRESH_INTERVAL_MS);
        }
    };

}